const initData = {
    list: JSON.parse(localStorage.getItem('list')) || [],
    list2: JSON.parse(localStorage.getItem('list2')) || []
}

const dataReducer = (state = initData, { type, payload }) => {

    switch (type) {

        case 'GET_LIST':

            localStorage.setItem('list', JSON.stringify(payload))

            return {
                ...state,
                list: payload
            }

        case 'GET_LIST2':

            localStorage.setItem('list2', JSON.stringify(payload))

            return {
                ...state,
                list2: payload
            }

        case 'FILTER_BTN':

            let newList = state.list.filter(item => item.nickName.includes(payload))

            localStorage.setItem('list', JSON.stringify(newList))

            return {
                ...state,
                list: newList
            }

        case 'EDIT_BTN':

            state.list.forEach((item) => {
                if (item.id === payload.id) {
                    item.nickName = payload.nickName
                    item.name = payload.name
                    item.email = payload.email
                    item.tel = payload.tel
                    item.flag = payload.flag
                }
            })

            localStorage.setItem('list', JSON.stringify(state.list))

            return {
                ...state,
                list: [...state.list]
            }

        case 'DETELE_BTN':

            state.list.splice(payload, 1)

            localStorage.setItem('list', JSON.stringify(state.list))

            return {
                ...state,
                list: [...state.list]
            }

        default:
            return {
                ...state
            }
    }

}

export default dataReducer